import Vue from "vue";
import VueRouter from "vue-router";
import HomeView from "../views/home/HomeView.vue";
import Recipe from "@/views/recipe/Recipe.vue";
import { getUserInfo } from "@/apis/user";
import store from "@/store";

Vue.use(VueRouter);

const viewsRoute = [
  // 菜谱详情
  {
    path: "/detail",
    name: "detail",
    title: "菜谱详情",
    component: () => import("@/views/detail/Detail.vue")
  },
  // 个人主页
  {
    path: "/user/space",
    name: "user-space",
    title: "个人主页",
    meta: {
      auth: true,//登录后才可以访问
    },
    component: () => import("@/views/space/UserSpace.vue"),
    // 重定向到works
    redirect: {//访问个人空间时，默认访问works
      name: "works"
    },
    //子路由
    children: [
      // 作品
      {
        path: "works",// user/space/works
        name: "works",
        title: "作品",
        meta: {
          auth: true,//登录后才可以访问
        },
        component: () => import("@/views/space/Works.vue"),
      },
      // 粉丝
      {
        path: "fans",// user/space/fans
        name: "fans",
        title: "粉丝",
        meta: {
          auth: true,//登录后才可以访问
        },
        component: () => import("@/views/space/Fans.vue"),
      },
      // 关注
      {
        path: "following",// user/space/following
        name: "following",
        title: "关注",
        meta: {
          auth: true,//登录后才可以访问
        },
        component: () => import("@/views/space/Fans.vue"),
      },
      // 收藏
      {
        path: "collection",// user/space/collection
        name: "collection",
        title: "收藏",
        meta: {
          auth: true,//登录后才可以访问
        },
        component: () => import("@/views/space/Works.vue"),
      },
    ]
  },
  // 个人资料
  {
    path: '/user/edit',
    title: '编辑个人资料',
    name: 'edit',
    component: () => import("@/views/space/Edit.vue"),
  },
  // 发布菜谱
  {
    path: "/create",
    name: "create",
    title: "发布菜谱",
    component: () => import("@/views/create/Create.vue")
  },
]

const routes = [
  // 首页
  {
    path: "/",
    name: "home",
    title: "首页",
    component: HomeView,
  },
  // 菜谱大全
  {
    path: "/recipe",
    name: "recipe",
    title: "菜谱大全",
    component: Recipe,
  },
  ...viewsRoute,
  // 登录
  {
    path: "/login",
    name: "login",
    component: () => import("@/views/login/Index.vue")
  },
];

const router = new VueRouter({
  mode: "history",
  base: process.env.BASE_URL,
  routes,
});

// 解决重复点击同一个导航报错问题
const originalPush = VueRouter.prototype.push;
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err)
}

// 导航守卫
// 进入路由的时候，都要向后台发送token，验证token是否合法
// 不论路由需不需要登录，都要展示用户信息，需要向后端发请求，获取用户信息
router.beforeEach(async (to, from, next) => {
  // 1. 获取token
  const token = localStorage.getItem('token');

  // 2. 获取用户信息（成功/失败）
  const res = await getUserInfo();//获取本人信息不需要传参
  // 3. 将用户信息同步到store（无论成功与否）
  store.commit("changeUserInfo", res.data);
  // 判断要访问的路由是否需要登录权限
  if (to.meta.auth) {
    // 判断登录状态 -> 可以正常访问
    if (res.code === 0) {// 获取用户信息成功
      next();
    }
    // 没有登录，或者登录过期，跳转至登录
    else {
      alert("请先登录！")
      next({ name: "login" })
    }
  } else {
    // 不需要登录权限，继续访问
    next()
  }
})

export default router;
